package com.heima.user.controller.v1;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.admin.AuthDto;
import com.heima.model.common.dtos.app.ApUserRealnameDto;
import com.heima.model.common.dtos.common.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.identity.pojos.Identity;
import com.heima.model.identity.pojos.cardFace;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.user.pojos.ProvinceCountyCity;
import com.heima.user.service.ApUserRealnameService;
import com.heima.common.identity.IdentityAuthenticationUtil;
import com.heima.user.service.ApUserService;
import com.heima.user.service.ProvinceCountyCityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/api/v1/auth")
public class ApUserAuthController {
    private static final String ID_CARD_FACE="face";
    private static final String ID_CARD_BACK="back";
    @Autowired
    private ApUserRealnameService apUserRealnameService;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ProvinceCountyCityService provinceCountyCityService;
    @Autowired
    private ApUserService apUserService;

    /**
     * 分页显示
     * @param apUserRealnameDto
     * @return
     */
    @PostMapping("/list")
    public ResponseResult list(@RequestBody ApUserRealnameDto apUserRealnameDto) {
        if(apUserRealnameDto.getPage() == null&&apUserRealnameDto.getSize() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();
        if(apUserRealnameDto.getStatus() != null){
            queryWrapper.eq(ApUserRealname::getStatus, apUserRealnameDto.getStatus());
        }
        IPage<ApUserRealname> page=new Page<>(apUserRealnameDto.getPage(),apUserRealnameDto.getSize());
        IPage<ApUserRealname> pageData = apUserRealnameService.page(page,queryWrapper);
        return ResponseResult.okResult(pageData.getRecords());
    }
    @PostMapping("/authPass")
    public ResponseResult authPass(@RequestBody AuthDto authDto) {
        //检验参数
        if(authDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //通过用户请求参数中的id获取身份信息
        ApUserRealname apUserRealname = apUserRealnameService.getById(authDto.getId());
        //通过身份证号和姓名调用实名认证工具类
        //用户姓名
        String name = apUserRealname.getName();
        //用户身份证号码
        String idno = apUserRealname.getIdno();
        try {
            //获取其身份信息
            Identity identity = JSON.parseObject(IdentityAuthenticationUtil.postData(name, idno), Identity.class);
            //判断身份信息是否有误
            if(!identity.getRespCode().equals("0000")){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,identity.getRespMessage());
            }
            //获取身份证正面所有文字信息与个人身份信息进行比对
            String face=apUserRealname.getFontImage();
            byte[] bytes = fileStorageService.downLoadFile(face);
            //String back=apUserRealname.getBackImage();
            //使用工具类获取身份证正面上的信息
            String card_face = IdentityAuthenticationUtil.postData2(ID_CARD_FACE, bytes);
            cardFace cardFace = JSON.parseObject(card_face, cardFace.class);
            if(cardFace.getSex().equals("男")){
                //M:男
                cardFace.setSex("M");
            }else{
                //F:女
                cardFace.setSex("F");
            }
            //使用工具类获取身份证正面上的信息
            //String card_back = IdentityAuthenticationUtil.postData2(ID_CARD_BACK, back, fileStorageService);
            //cardBack cardBack = JSON.parseObject(card_back, cardBack.class);
            //判断该市是否为省直辖市
            String address="";
            LambdaQueryWrapper<ProvinceCountyCity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProvinceCountyCity::getCounty,identity.getCounty());
            ProvinceCountyCity provinceCountyCity = provinceCountyCityService.getOne(wrapper);
            //如果是省直辖市,则去掉地级市，地址为省+省直辖市
            if(provinceCountyCity!=null){
                address=identity.getProvince()+identity.getCounty();
            }else{
                //如果不是省直辖市，则需要添加地级市，地址为省+地级市+县/市
                address=identity.getProvince()+identity.getCity()+identity.getCounty();
            }
            //根据身份证正面上的信息和用户自己输入的信息进行比对，比对成功则通过
            ResponseResult auditor = Auditor(identity, cardFace,address);
            if(!auditor.getCode().equals(200)){
                return auditor;
            }
            //将审核状态更改为审核通过
            apUserRealname.setStatus(9);
            apUserRealname.setUpdatedTime(new Date());
            apUserRealnameService.updateById(apUserRealname);
            //更新用户信息表中是否实名认证字段
            LambdaUpdateWrapper<ApUser> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ApUser::getId,apUserRealname.getUserId()).set(ApUser::getIsIdentity_authentication,1);
            apUserService.update(updateWrapper);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }catch (Exception e){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"身份认证失败");
        }
    }
    private ResponseResult Auditor(Identity identity,cardFace cardFace,String address) {
        if(!identity.getIdno().equals(cardFace.getNum())){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"用户身份信息与图片不符,建议驳回");
        }
        if(!identity.getName().equals(cardFace.getName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"用户个人信息与图片不符,建议驳回");
        }
        if(!identity.getBirthday().equals(cardFace.getBirth())){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"用户个人信息与图片不符,建议驳回");
        }
        if(!identity.getSex().equals(cardFace.getSex())){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"用户个人信息与图片不符,建议驳回");
        }
        if(!cardFace.getAddress().contains(address)){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"用户个人信息与图片不符,建议驳回");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    @PostMapping("/authFail")
    public ResponseResult authFail(@RequestBody AuthDto authDto) {
        ApUserRealname apUserRealname = apUserRealnameService.getById(authDto.getId());
        //设置为审核未通过
        apUserRealname.setStatus(2);
        //设置未通过原因
        apUserRealname.setReason(authDto.getMsg());
        apUserRealname.setUpdatedTime(new Date());
        //更新审核状态和原因
        apUserRealnameService.updateById(apUserRealname);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
